package com.crazy.practice.boot.core;

import com.crazy.entity.IpInfoEntity;
import com.crazy.util.IpAddressUtils;
import com.crazy.util.IpUtils;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author panyonghui
 * @describe 参数前置处理
 * @date 2022/8/19 10:58
 */
@Slf4j
@ControllerAdvice
public class BeforeParamProcessAdvice {

    @ModelAttribute
    public void paramProcess(Model model, HttpServletRequest request) {
        Map headerMap = new HashMap(10);
        String ip = IpUtils.getIpAddress(request);
        headerMap.put("ip", ip);
        IpInfoEntity ipInfoEntity = null;
        try {
            ipInfoEntity = IpAddressUtils.ipInfoByLocal(ip);
        } catch (IOException e) {
            ipInfoEntity = IpAddressUtils.ipInfoByIpApi(ip);
            log.error("ip信息获取失败", e);
        } catch (GeoIp2Exception e) {
            log.error("ip信息获取失败", e);
        }
        headerMap.put("iPAttr", ipInfoEntity);
        model.addAttribute("headerMap", headerMap);
    }

}
